package org.millioncall.yueyoga.admin.model;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.UUID;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

//created by zangjy on 2012-3-30
public class DbFile implements Serializable {
	private static final long serialVersionUID = 15333725290598514L;
	private Logger logger = LoggerFactory.getLogger(DbFile.class);
	private String id = UUID.randomUUID().toString().replace("-", "");// 文件编号
	private int type = 0;// 文件类型 0变通文件，1图片，2数据库备份文件
	private String fileName;// 文件名称
	private int length;// 文件长度
	private Long lastModified;// 最后修改时间
	private byte[] content;// 文件内容
	private int hashCode = Integer.MIN_VALUE;

	public DbFile() {
	}

	public DbFile(Short type, String fileName, Integer length, Long lastModified, byte[] content) {
		this.type = type;
		this.fileName = fileName;
		this.length = length;
		this.lastModified = lastModified;
		this.content = content;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
		this.hashCode = Integer.MIN_VALUE;
	}

	public int getType() {
		return type;
	}

	public void setType(int type) {
		this.type = type;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public int getLength() {
		return length;
	}

	public void setLength(int length) {
		this.length = length;
	}

	public Long getLastModified() {
		return lastModified;
	}

	public void setLastModified(Long lastModified) {
		this.lastModified = lastModified;
	}

	public byte[] getContent() {
		return content;
	}

	public void setContent(byte[] content) {
		this.content = content;
	}

	public File convertToFile(File file) {
		try {
			FileUtils.writeByteArrayToFile(file, this.getContent());
		} catch (IOException e) {
			logger.error("IO异常", e);
		}
		return file;
	}

	public boolean equals(Object obj) {
		if(obj == null) {
			return false;
		}

		if(!(obj instanceof DbFile)) {
			return false;
		} else {
			DbFile auth = (DbFile)obj;
			if(this.getId() == null || auth.getId() == null) {
				return false;
			} else {
				return (this.getId().equals(auth.getId()));
			}
		}
	}

	public int hashCode() {
		if(this.hashCode == Integer.MIN_VALUE) {
			if(this.getId() == null) {
				return super.hashCode();
			} else {
				String hashStr = this.getClass().getName() + ":" + this.getId().hashCode();
				this.hashCode = hashStr.hashCode();
			}
		}
		return this.hashCode;
	}
}
